Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms

Imports DbfDotNet

Public Partial Class IndividualsForm
	Inherits Form
	Private individuals As DbfTable(Of Individual)

	Const ADD_INDIVIDUALS_COUNT As Integer = 10000

	Public Sub New()
        For Each fi As IO.FileInfo In New System.IO.DirectoryInfo(".").GetFiles("*.ndx")
            fi.Delete()
        Next

		InitializeComponent()
		individuals = New DbfTable(Of Individual)("individuals.dbf", Encoding.ASCII, DbfVersion.dBaseIV)

		tableView1.DbfTable = individuals
		Me.addToolStripMenuItem.Text = String.Format("Add {0:0,0} individuals", ADD_INDIVIDUALS_COUNT)
		RefreshBar()
	End Sub

	Private Sub quitToolStripMenuItem_Click(sender As Object, e As EventArgs)
		Close()
	End Sub

	Private Sub RefreshBar()
		toolStripStatusLabel1.Text = String.Format("Ready ({0} records in database).", individuals.RecordCount)
	End Sub

	Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs)
		individuals.Close()
	End Sub

	Private Sub addToolStripMenuItem_Click(sender As Object, e As EventArgs)
		Dim k As Integer = individuals.RecordCount
		For i As Integer = 0 To ADD_INDIVIDUALS_COUNT - 1
            Dim newIndiv As Individual = individuals.NewRecord()
			Dim male As Boolean = RandomData.RandomBool()
			newIndiv.FIRSTNAME = (If(male, RandomData.RandomMaleFirstname(), RandomData.RandomFemaleFirstname()))
			Dim middleName As String = (If(male, RandomData.RandomMaleFirstname(), RandomData.RandomFemaleFirstname()))
			If middleName <> newIndiv.FIRSTNAME Then
				newIndiv.MIDDLENAME = middleName
			End If
			newIndiv.LASTNAME = RandomData.RandomLastName()
			newIndiv.STATE = RandomData.RandomState()
			newIndiv.DOB = RandomData.RandomDob()
			k += 1
			newIndiv.SaveChanges()
		Next
		RefreshBar()
		tableView1.RefreshGrid()
	End Sub

	Private Sub clearFileToolStripMenuItem_Click(sender As Object, e As EventArgs)
	End Sub

	Private Sub tableView1_MouseDoubleClick(sender As Object, e As MouseEventArgs)
		Dim individual As Individual = Nothing

        If tableView1.GetRow(CType(tableView1.FocusedItem.Index, Int32), individual) Then
            Dim detailForm As DetailForm = New DetailForm()
            detailForm.ReadIndividual(individual)
            If detailForm.ShowDialog() = DialogResult.OK Then
                detailForm.WriteIndividual(individual)
                individual.SaveChanges()
            End If
        End If
	End Sub

	Private Sub clearFileToolStripMenuItem1_Click(sender As Object, e As EventArgs)
		individuals.EmptyTable()
		tableView1.RefreshGrid()
		RefreshBar()
	End Sub

End Class
